import React, { useState, useEffect } from 'react';
import { Link, history } from 'umi';
import {
  Space,
  Checkbox,
  Form,
  Input,
  Select,
  Table,
  Badge,
  message,
  Popconfirm,
  Button,
  Modal,
} from 'antd';
import type { SizeType } from 'antd/es/config-provider/SizeContext';
import axios from 'axios';
import { connect } from 'umi';
import { RedoOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import './style/index.less'
var _ = require('lodash');
type Props = {};

const Index = (props: any) => {
  const [form] = Form.useForm();

  const onFinish = (values: any) => {
    console.log(values);
    dispatch({
      type: 'AllDate/SEARCH',
      payload: values,
    });
    history.push('/pages/Articlemanagement/All');
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('state:', errorInfo);
  };

  const [size, setSize] = useState<SizeType>('large');

  const { dispatch, list, ArticleList, Searchlist }: any = props;

  //获取分类数据
  useEffect(() => {
    dispatch({
      type: 'AllDate/getArticle',
    });
    console.log(form);
  }, []);

  //重置
  const Reset = () => {
    form.resetFields();
  };

  //获取页面全部数据
  useEffect(() => {
    dispatch({
      type: 'AllDate/AddDate',
    });
  }, []);

  interface DataType {
    key: React.Key;
    name: string;
    age: number;
    address: string;
    isCommentable: any;
  }

  //二次确认框
  const confirm = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    message.success('删除成功');
  };

  const cancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
    message.error('取消删除');
  };
  const columns: ColumnsType<DataType> = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '状态',
      dataIndex: 'isCommentable',
      render: (isCommentable) => <p>{isCommentable===true?
        (<>
          <Badge status="success" />
          <a style={{ marginLeft: '5px' }}>已发布</a>
        </>)
        :(<>
          <Badge status="warning" />
          <a style={{ marginLeft: '5px' }}>已发布</a>
        </>)}</p>
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (category) => <a>{category.label}</a>,
    },
    // {
    //   title: '标签',
    //   dataIndex: 'tags',
    //   key: 'tags',
    //   render: (tags) => <a style={{background:"blue",color:"white",padding:'10px 10px'}}>{tags[0].label}</a>,
    // },
    {
      title: '阅读量',
      dataIndex: 'views',
      key: 'views',
      render: (views) => (
        <a
          style={{
            background: 'rgb(82, 196, 26)',
            color: 'white',
            padding: '5px 10px',
            borderRadius: '10px',
          }}
        >
          {views}
        </a>
      ),
    },
    {
      title: '喜欢数',
      dataIndex: 'likes',
      key: 'likes',
      render: (likes) => (
        <a
          style={{
            background: 'rgb(235, 47, 150)',
            color: 'white',
            padding: '5px 10px',
            borderRadius: '10px',
          }}
        >
          {likes}
        </a>
      ),
    },
    {
      title: '发布时间',
      dataIndex: 'createAt',
      key: 'createAt',
    },
    {
      title: '删除',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a>编辑 {record.name}</a>
          <a onClick={() => {
              tj(record);
            }}>{ArticleList[0].isCommentable?"撤销首焦":"推荐首焦"}</a>
          <a onClick={showModal}>查看访问</a>
          <Popconfirm
            title="确认要删除吗?"
            onConfirm={confirm}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
            onClick={() => {
              del(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
//推荐首焦
const tj=(record:any)=>{
  ArticleList.forEach((item:any) => {
    if(item.id===record.id){
      ArticleList[0].isCommentable=!ArticleList[0].isCommentable
    }
  });
  
  console.log(ArticleList[0].isCommentable);
  
}
  //删除
  const del = (key: any) => {
    dispatch({
      type: 'AllDate/DEL',
      payload: key,
    });
  };
  //查看访问弹框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [loading, setLoading] = useState(false);

  const start = () => {
    setLoading(true);
    // ajax request after empty completing
    setTimeout(() => {
      setSelectedRowKeys([]);
      setLoading(false);
    }, 1000);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  //图表
  return (
    <div className="allbox">
      <div id="search">
        <div className="frombox">
          <Form
            form={form}
            className="form"
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item label="标题" name="title" className="formitem">
              <Input placeholder="请输入文章标题" className="inp" />
            </Form.Item>
            <Form.Item label="状态" name="state" className="formitem">
              <Select className="inp">
                <Select.Option value="已发布">已发布</Select.Option>
                <Select.Option value="草稿">草稿</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item label="分类" name="classify" className="formitem">
              <Select className="inp">
                {list &&
                  list.map((item: any, index: any) => {
                    return (
                      <Select.Option key={index} value={item.label}>
                        {item.label}
                      </Select.Option>
                    );
                  })}
              </Select>
            </Form.Item>

            <div className="btn">
              <Button
                className="an"
                type="primary"
                size={size}
                htmlType="submit"
              >
                搜索
              </Button>
              <Button className="an" size={size} onClick={_.debounce(Reset,2000)}>
                重置
              </Button>
            </div>
          </Form>
        </div>
      </div>
      <div className="Allmenubox">
        <div className="newlyBuild">
          <Button className="newlyBuildbtn" type="primary">
            + 新建
          </Button>
          <span
            style={{
              width: 50,
              height: 50,
              textAlign: 'center',
              lineHeight: 2.5,
              cursor: 'pointer',
            }}
          >
            <RedoOutlined style={{ fontSize: '20px' }} />
          </span>
        </div>
        <div className="Tablebox">
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={ArticleList}
          />
        </div>
      </div>

      {/* 查看访问弹框 */}
      <Modal
        title="访问统计"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText
        okText
      >

      </Modal>
    </div>
  );
};

export default connect(({ AllDate }: any) => AllDate)(Index);
